package com.atguigu.JUCAuxiliaryClass;

import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * ClassName: SemaphoreDemo
 * Package: com.atguigu.JUCAuxiliaryClass
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/29 20:46
 * version: 1.0
 */
public class SemaphoreDemo {
    //案例：三个车位，六辆车（限流）
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);  //构建信号量对象
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//线程处于阻塞，获取信号执行
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    Thread.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName()+"开出车位");
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },"编号第"+i+"车位").start();
        }

    }
}
